import {LockOutlined, UserOutlined} from '@ant-design/icons';
import {
  LoginForm,
  ProFormText,
} from '@ant-design/pro-components';
import { history, useIntl, useModel, Helmet } from '@umijs/max';
import { Alert, message } from 'antd';
import Settings from '../../../../config/defaultSettings';
import React, { useState } from 'react';
import IHttp from '@/services/http.service';
import {firstValueFrom} from "rxjs"
import IStorage from "@/services/storage.service";
import { flushSync } from "react-dom"
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};



const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const handleSubmit = async (values: API.LoginParams) => {

    // await Promise.reject()
    const res = await firstValueFrom(IHttp.login({ ...values }));
    if (res.status) {
      message.success("登陆成功!")
      flushSync(() => {
        setInitialState(s => ({...s, currentUser: res.data.user as API.CurrentUser}))
      })

      IStorage.setUserTicket(res.data.ticket as string)
      const { location } = history
      const redirectUri = new URLSearchParams(location.search).get("redirect") || "/"
      history.push(redirectUri);
    }
    // message.error(res.message || "账户或密码错误!")
  };

  return (
    <div className={`login-page-wrap flex flex-column h-[100vh] bg-[url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')]`} style={{backgroundSize: "100% 100%"}}>
      <Helmet>
        <title>
          登录 - {Settings.title}
        </title>
      </Helmet>
      <div className="flex-1 flex items-center justify-center">
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          className={"admin-test-2"}
          rootClassName={"admin-test"}
          initialValues={{
            autoLogin: true,
          }}
          title={"登录系统"}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <ProFormText
            name="username"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined />,
            }}
            placeholder={"用户名"}
            rules={[
              {
                required: true,
                message: "请输入用户名!",
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined />,
            }}
            placeholder={"密码"}
            rules={[
              {
                required: true,
                message: "请输入密码！",
              },
            ]}
          />
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
